package cn.edu.scau.cmil.linwei.comprehensive.Controller;

import cn.edu.scau.cmil.linwei.comprehensive.Script.DataField;
import cn.edu.scau.cmil.linwei.comprehensive.Script.PartScoreData;
import cn.edu.scau.cmil.linwei.comprehensive.Script.Score;
import cn.edu.scau.cmil.linwei.comprehensive.Script.StudentData;
import cn.edu.scau.cmil.linwei.comprehensive.util.DataIO;
import cn.edu.scau.cmil.linwei.comprehensive.util.StageManager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class StudentReportWindowsController implements Initializable {
    public BorderPane borderPane;
    //显示学生成绩的tableView
    public TableView table;
    public TableColumn CourseNameTableColumn;//课名
    public TableColumn AttendTableColumn;//考勤分
    public TableColumn ExamTableColumn;//测验分
    public TableColumn WorkTableColumn;//作业分
    public TableColumn FinalExamTableColumn;//期末分
    public TableColumn TotalScoreTableColumn;//总评
    //显示成绩区间的tableView
    public TableView parttable;
    public TableColumn sectionTableColumn;//成绩区间
    public TableColumn numberTableColumn;//课程
    public TableColumn percentTableColumn;//百分比

    public Text userIDText;
    public Text StudentInfoText;

    //标题栏最小化、关闭、拖拽
    private double oldStageX,oldStageY,oldScreenX,oldScreenY;//点击时记录窗口的XY
    //最小化
    public void MinButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setIconified(true);
    }//设置最小化按钮点击时发生的活动选项
    //关闭
    public void CloseButtonClicked(){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.close();
    }//设置关闭按钮点击时发生的活动选项
    //鼠标拖拽
    public void MousePressed(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        oldStageX = stage.getX();//事件相对于MouseEvent源的原点的水平位置，即获取当前鼠标位置
        oldStageY = stage.getY();//事件相对于MouseEvent源的原点的垂直位置，即获取当前鼠标位置
        oldScreenX = event.getScreenX();//返回事件的绝对水平位置，即获取窗口左上角位置
        oldScreenY = event.getScreenY();//返回事件的绝对垂直位置，即获取窗口左上角位置
    }

    public void MouseDragged(MouseEvent event){
        Stage stage = (Stage) borderPane.getScene().getWindow();
        stage.setX(event.getScreenX()-oldScreenX+oldStageX);
        stage.setY(event.getScreenY()-oldScreenY+oldStageY);
    }

    //页面转换
    public void GoBack(){//返回教师主界面
        CloseStudentReportWindows();//关闭当前界面
        openTeacherMainWindows();//打开教师主界面
    }//注销

    public void openTeacherMainWindows() {
        Stage stage = StageManager.STAGEMAP.get("TeacherMainWindows");
        StageManager.STAGEMAP.remove("TeacherMainWindows");//在MAP中删除TeacherMainWindows页面的Stage
        StageManager.CONTROLLERMAP.remove("TeacherMainWindows");//在MAP中删除TeacherMainWindows页面的Controller
        stage.show();
    }//打开主界面

    public void CloseStudentReportWindows(){
        Stage stage = (Stage)borderPane.getScene().getWindow();//通过布局获取场景再获取舞台
        StageManager.STAGEMAP.put("StudentReportWindows",stage);//保存舞台
        StageManager.CONTROLLERMAP.put("StudentReportWindowsController",this);//保存控制器
        stage.close();//关闭舞台
    }//关闭本窗口

    //设置Text
    public void setUserIDText(){
        userIDText.setText(DataField.LoginedUser.Name);
    }//设置欢迎词

    public void setStudentInfoText(){
        StudentInfoText.setText("学号："+DataField.LoginedStudent.ID+
                "\t姓名："+DataField.LoginedStudent.Name+
                "\t班级："+DataField.LoginedStudent.myclass.StudentGrade+"级"+
                            DataField.LoginedStudent.myclass.StudentMajor+"专业"+
                            DataField.LoginedStudent.myclass.StudentClass+"班");
    }
    //TableView表格数据操作
    //1.学生成绩主表格
    public final ObservableList<StudentData> Maindata = FXCollections.observableArrayList();
    public ArrayList<Score> SearchedScoredata;

    public void InitMainTable(){
        SearchedScoredata = new ArrayList<>();
        //设置六列，将数据关联到表中的列
        CourseNameTableColumn.setCellValueFactory(new PropertyValueFactory<>("CourseName"));//第一列中的数据关联StudentData中的CourseName
        AttendTableColumn.setCellValueFactory(new PropertyValueFactory<>("Attend"));
        ExamTableColumn.setCellValueFactory(new PropertyValueFactory<>("Exam"));
        WorkTableColumn.setCellValueFactory(new PropertyValueFactory<>("Work"));
        FinalExamTableColumn.setCellValueFactory(new PropertyValueFactory<>("FinalExam"));
        TotalScoreTableColumn.setCellValueFactory(new PropertyValueFactory<>("TotalScore"));
        table.setItems(Maindata);//数据关联到tableView
    }//初始化主表格

    public void SearchforMainTable(){
        //在ScoreData中查找ID相同的学生信息，并add到data中，tableView会实时更新
        Score score;
        String id = DataField.LoginedStudent.ID;

        for(int i = 0; i<DataField.scoreData.size(); i++){
            score = DataField.scoreData.get(i);
            if(score.StudentID.equals(id)){
                //如果学生ID相同，提取课名，考勤，测验，作业，期末，对总评=考勤+测验+作业+期末进行更新
                int total = score.Attend + score.Exam + score.Work + score.FinalExam;
                score.TotalScore = total;
                StudentData sd = new StudentData(score.CourseName,score.Attend,
                        score.Exam,score.Work,score.FinalExam,score.TotalScore);
                SearchedScoredata.add(score);//把搜索到的学生信息添加进去，查找区间的时候用
                Maindata.add(sd);//把学生信息加进data中
            }
        }
        try {
            DataIO.ScoreWrite();//把更改的信息写入文件，否则更新的总评不会被保存下来
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//为主表格搜索数据

    //2.成绩区间表格
    public final ObservableList<PartScoreData> Partdata = FXCollections.observableArrayList();

    public void InitPartTable(){
        //设置三列，将数据关联到表中的列
        sectionTableColumn.setCellValueFactory(new PropertyValueFactory<>("section"));//第一列中的数据关联PartScoreData中的section
        numberTableColumn.setCellValueFactory(new PropertyValueFactory<>("number"));//第二列中的数据关联PartScoreData中的number
        percentTableColumn.setCellValueFactory(new PropertyValueFactory<>("percent"));

        parttable.setItems(Partdata);//数据关联到tableView
    }

    public void SearchforPartTable(){
        //在SearchedScoredata中统计各区间的科目数，并计算出百分比，add到data中，tableView会实时更新
        String[] sections = {"0-59","60-69","70-79","80-89","90-100"};
        int[] numbers = {0 , 0 , 0 , 0 , 0};
        double[] percents = {0.0 , 0.0 , 0.0 , 0.0 , 0.0};
        Score score;
        for(int i = 0; i<SearchedScoredata.size(); i++){
            score = SearchedScoredata.get(i);
            if(score.TotalScore<=59){
                numbers[0]++;
            }
            else if(score.TotalScore<=69){
                numbers[1]++;
            }
            else if(score.TotalScore<=79){
                numbers[2]++;
            }
            else if(score.TotalScore<=89){
                numbers[3]++;
            }
            else{
                numbers[4]++;
            }
            double totalnumber = 0;
            for(int n:numbers){
                totalnumber+=(double)n;
            }
            for(int j =0 ; j<percents.length ; j++){
                int x = (int)((double) numbers[j]/totalnumber*1000+0.5);
                percents[j]=(double)x/10;
            }
        }//for
        for(int i =0;i<5;i++){
            PartScoreData tmp = new PartScoreData(sections[i],numbers[i],Double.valueOf(percents[i])+"%");
            Partdata.add(tmp);//把学生信息添加进
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {//初始化函数在执行FXMLLoader时执行
        setUserIDText();
        setStudentInfoText();

        InitMainTable();
        SearchforMainTable();

        InitPartTable();
        SearchforPartTable();
    }



}
